package com.lkd.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.contract.VmStatusContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    //创建工单
    @Override
    public Boolean productionOrderSave(TaskViewModel tvm) {
        if(hasTask(tvm.getInnerCode(),tvm.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //校验售货机状态
        checkCreateOrder(tvm.getInnerCode(),tvm.getProductType());
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(tvm, taskEntity);
        //设置工单编号
        taskEntity.setTaskCode(generateTaskCode());
        //设置工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //设置工单类型
        taskEntity.setProductTypeId(tvm.getProductType());
        VmVO vm = vmService.getVMInfo(tvm.getInnerCode());
        taskEntity.setRegionId(vm.getRegionId());
        taskEntity.setAddr(vm.getNodeAddr());
        this.save(taskEntity);
        String taskCode = taskEntity.getTaskCode();
        //如果是补货工单，向工单明细表插入记录
        if (tvm.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
            TaskDetailsEntity taskDetails = new TaskDetailsEntity();
            for (TaskDetailsViewModel detail : tvm.getDetails()) {
                BeanUtils.copyProperties(detail, taskDetails);
            }
            LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TaskEntity::getTaskCode,taskCode);
            TaskEntity taskEntity1 = getOne(queryWrapper);
            taskDetails.setTaskId(taskEntity1.getTaskId());
            taskDetailsService.save(taskDetails);
        }

        //自动更新工单列表
        updateTaskZet(taskEntity,1);
        return true;
    }



    /**
     * 接受工单
     * 如果订单状态不是待处理，则不能接受；
     */
    @Override
    public void accept(TaskEntity task) {
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_CREATE) {
            try {
                throw new Exception("该订单状态不是待处理状态");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        updateById(task);
    }



//取消工单
    @Override
    public boolean cancelTask(TaskEntity task, CancelTaskViewModel ctvm) {
        //如果工单状态是已取消或已完成，则抛出异常。
       if(task.getTaskStatus()==VMSystem.TASK_STATUS_CANCEL||task.getTaskStatus()==VMSystem.TASK_STATUS_FINISH){
           throw new LogicException("该工单已取消或者已完成");
       }
     //   修改工单状态为取消，记录拒绝原因。
        task.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
       task.setDesc(ctvm.getDesc());
        updateById(task);
        updateTaskZet(task,-1);
        return true;

    }

    /*
    * 完成工单
    * */
    @Override
    public boolean finishTask(TaskEntity task) {
        //如果工单状态是已取消或已完成，则抛出异常。
        if(task.getTaskStatus()==VMSystem.TASK_STATUS_CANCEL||task.getTaskStatus()==VMSystem.TASK_STATUS_FINISH){
            throw new LogicException("该工单已取消或者已完成");
        }
         //  如果工单类型为投放或者撤机，更改售货机售货机状态
        if(task.getProductTypeId()==VMSystem.TASK_TYPE_DEPLOY|| task.getProductTypeId()==VMSystem.TASK_TYPE_REVOKE) {
            if (task.getProductTypeId() != null && task.getInnerCode() != null) {
                TaskCompleteContract tcc = new TaskCompleteContract();
                tcc.setTaskType(task.getProductTypeId());
                tcc.setInnerCode(task.getInnerCode());
                changVmstatus(tcc);
            }
        }
        //  如果工单类型为补货，更改售货机库存
        if(task.getProductTypeId()==VMSystem.TASK_TYPE_SUPPLY){
            changVmstores(task);
        }

      // 修改工单状态为完成。
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
     return    updateById(task);
    }

    //生成工单编号
    public String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //日期字符串
        String key = "lkd.task.data." + date;//redis    key
        Object object = redisTemplate.opsForValue().get(key);
        if (object == null) {
            redisTemplate.opsForValue().set(key, 1l, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(key, 1).toString(), 4, '0');
    }

    //创建工单校验
    public void checkCreateOrder(String innerCode, int productType) {
        //根据设备编号查询设备
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        if (vmInfo == null) {
            throw new LogicException("设备校验失败");
        }
        //如果是投放工单，则状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            {
                throw new LogicException("该设备已在运营");
            }
        }
        //如果是补货工单，则状态为不在运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            {
                throw new LogicException("该设备不在在运营");
            }
        }
        //如果是撤机工单，则状态为不在运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            {
                throw new LogicException("该设备不在在运营");
            }
        }
    }
    //校验同一台设备是否有未完成的工单
    public  boolean  hasTask(String  innerCode,int productionType){
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda().select(TaskEntity::getTaskId).eq(TaskEntity::getInnerCode,innerCode).eq(TaskEntity::getProductTypeId,productionType).le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return  this.count(qw)>0;
    }

    @Autowired
    private MqttProducer  mqttProducer;
//(投放和撤机)运维工单下发方法封装
    public void   changVmstatus( TaskCompleteContract  tcc){
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,2,tcc);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
    //(补货)运维工单下发方法封装
  public  void   changVmstores(TaskEntity task){
      SupplyChannel supplyChannel = new SupplyChannel();
      SupplyContract supplyContract = new SupplyContract();
      List<SupplyChannel> channelList = new ArrayList<>();
      List<TaskDetailsEntity> detailsList = taskDetailsService.getByTaskId(task.getTaskId());
      //从工单明细表中提取数据导supplyChannel
      detailsList.forEach(c->{
          supplyChannel.setChannelId(c.getChannelCode());
          supplyChannel.setCapacity(c.getExpectCapacity());
          channelList.add(supplyChannel);
      });
    /*  //从工单明细表中提取数据导supplyChannel
      for (TaskDetailsEntity taskDetailsEntity : detailsList) {
          BeanUtils.copyProperties(taskDetailsEntity,supplyChannel);
          supplyChannel.setChannelId(taskDetailsEntity.getChannelCode());
          supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
          channelList.add(supplyChannel);
      }*/
      supplyContract.setInnerCode(task.getInnerCode());
      supplyContract.setSupplyData(channelList);
      try {
          mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,2, supplyContract);
      } catch (JsonProcessingException e) {
          e.printStackTrace();
      }
  }


  /*
  * 更新工单量列表
  * TaskEntity,score
  * */
    public void  updateTaskZet( TaskEntity taskEntity,int score){
//如果是补货工单，则是运营，roleCode=1002，//运营员
// 如果不是补货工单，则是运维，roleCode=1003，//运维员
        String roleCode="1003";
        if(taskEntity.getProductTypeId()==2){
            //是补货
           roleCode="1002";
        }
String   key=VMSystem.REGION_TASK_KEY_PREF+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
        +"."+ taskEntity.getRegionId()+"."+roleCode;
     redisTemplate.opsForZSet().incrementScore(key,taskEntity.getTaskId(),score);
    }


    //工单分页查询
    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime,LocalDate.parse(start,DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }


    //获取一天内工单最少的用户
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {

        //如果是补货工单，则是运营，roleCode=1002，//运营员
// 如果不是补货工单，则是运维，roleCode=1003，//运维员
        String roleCode="1002";
        if(isRepair){
            //是补货
            roleCode="1003";
        }
        String   key=VMSystem.REGION_TASK_KEY_PREF+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                +"."+ regionId+"."+roleCode;
        //从redis中获取当前工单最少的用户，排在第一个的用户
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 1);
        //如果set为空，则说明该区域没有运维人员
        if(set.isEmpty()||set==null){
            throw  new LogicException("该区域没有运维人员");
        }
  return  (Integer) set.stream().collect(Collectors.toList()).get(0);
    }
}
